<template>
  <div class="app-container">
      <el-form :inline="true" :model="form" class="demo-form-inline" v-show="showSearch">
          <el-form-item label="所属机构">
            <el-select v-model="queryParams.payDeptId" placeholder="请选择机构">
              <el-option
                v-for="dept in allDept"
                :key="dept.deptId"
                :label="dept.deptName"
                :value="dept.deptId"
              ></el-option>
            </el-select>
          </el-form-item>
            <el-form-item label="支出科目名称">
            <el-input v-model="queryParams.payName" placeholder="请输入支出科目名称"></el-input>
          </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="queryParams.payState" >
                <el-option label="正常" value="0"></el-option>
                <el-option label="停用" value="1"></el-option>
               </el-select>
            </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="querypaySubject">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleAdd">新增</el-button> 
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="resestTable">重置</el-button>
          </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
            >导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>
      <el-table
        :data="form"
        style="width: 100%"
        :default-sort = "{prop: 'payCoding', order: 'descending'}"
        >
        <el-table-column
          align="center"
          prop="sysDept.deptName"
          label="所属机构"
          sortable
          width="222">
        </el-table-column>
        <el-table-column
          align="center"
          prop="payCoding"
          label="编码"
          width="222"
          sortable>
        </el-table-column>
        <el-table-column
          align="center"
          prop="payName"
          label="名称"
          width="222"
          sortable>
        </el-table-column>
        <el-table-column
          align="center"
          prop="payState"
          label="状态"
          width="222"
          sortable>
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.payState==0">正常</el-tag>
            <el-tag type="danger" v-if="scope.row.payState==1">停用</el-tag>        
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="static"
          label="操作"
          width="222">
          <template slot-scope="scope">
              <el-button @click="updatePaySubject(scope.row)"
                size="mini"
                type="text"
                >编辑</el-button>
                <el-button @click="handleView(scope.row)" 
                style="margin-left: 16px;"
                size="mini"
                type="text"
                >查看</el-button>
            </template>
        </el-table-column>
      </el-table>
      <div class="block">
      <span class="demonstration"></span>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"  
      ></pagination>
      </div>
    <!-- 新增及修改-->
      <el-dialog :title="title" :visible.sync="open">
              <el-form :model="form2"  ref="form1" :rules="rules" label-width="130px" class="frame">
                <el-form-item label="所属机构" prop="payDeptId">
                  <el-select v-model="form2.payDeptId" placeholder="请选择机构">
                    <el-option
                      v-for="dept in allDept"
                      :key="dept.deptId"
                      :label="dept.deptName"
                      :value="dept.deptId"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="支出科目编码" prop="payCoding">
                  <el-input  v-model="form2.payCoding" rules="payCoding"></el-input>
                </el-form-item>
                <el-form-item label="支出科目名称"  prop="payName">
                  <el-input v-model="form2.payName" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="payState">
                  <el-radio-group v-model="form2.payState">
                    <el-radio :label="0" >正常</el-radio>
                    <el-radio :label="1" >停用</el-radio>
                  </el-radio-group>                  
                </el-form-item>              
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
              </div>
      </el-dialog>

      <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
      </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
    </el-dialog>

      <!-- 详细 -->
    <el-dialog title="详情" :visible.sync="drawer" width="700px" append-to-body>
      <el-form   label-width="100px" size="mini">
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属机构：">{{ this.dtn.deptName}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="编码：">{{ form2.payCoding }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="名称：">{{ form2.payName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态：">
              <div v-if="form2.payState === 0">正常</div>
              <div v-else-if="form2.payState === 1">停用</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="drawer= false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import {queryAllPaySybject,queryDeptById,save,querySysDept,queryIdByCoding,edit} from "@/api/system/paySubject";
import { getToken } from "@/utils/auth";
export default {
//import引入的组件需要注入到对象中才能使用
components: {},
data() {
  //这里存放数据

    //表单校验
       var validatePayCoding = (rule,value,callback) => {
        if (!value){
          return callback(new Error('请输入编码'));
        }
        if(this.title == '新增'){
          queryIdByCoding({"payCoding":value}).then(resp =>{
          if(resp.data){return callback("编码已存在");
        }else{
            callback();
          }
        })
      }else{
        callback();
      }  
    }
        
  return {
      // 遮罩层
      loading: true,
      // 是否显示弹出层
      open: false,
      drawer: false,
      // 显示搜索条件
      showSearch: true,
       // 弹出层标题
      title: "",
      //表单参数
      form1: {},
      form: {},
      form2: {},
      //无法识别deptname，所以重新第一个变量对其赋值
      dtn: '',
      formLabelWidth: '120px',
      //部门选项
      allDept: [],
      //用户导入参数
       // 用户导入参数
       upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/aqsc/paySubject/importData"
      },
      // 查询参数
      queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
      // form 表单校验
      rules: {
        payDeptId: [
          { required: true, message: '请选择所属机构', trigger: 'change' },
        ],
        payCoding: [
          {required: true, validator:validatePayCoding,trigger: 'blur'},
        ],
        payName: [
          { required: true, message: '请输入支出科目名称',trigger: 'blur'}
        ],
        payState: [
          { required: true,message: '请选择状态',trigger: 'blur'}
        ]
      },
    }

},
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
  //查询列表
    getList(){
      this.loading=true;
      console.info(JSON.stringify(this.queryParams))
      queryAllPaySybject(this.queryParams).then(response =>{
        this.form = response.rows;
        this.total = response.total;
        this.loding = false;
      }) 
    },
   //遍历dept
    getDeptName(){
      querySysDept().then(response =>{
          this.allDept = response.data;
         
      })
   },
   //查询
    querypaySubject(){
      this.queryParams.pageNum = 1;
      this.getList();
   },
   //表单重置
    resestTable(){
      this.queryParams={},
      this.querypaySubject();
   },
   //新增按钮
    handleAdd(){
        this.form = {}
        this.open = true;
        this.title = "添加用户";
    
   },
   //查看按钮
   handleView(row){
      queryDeptById(row.id).then(response =>{
        this.form2 = response;
        this.dtn = this.form2.sysDept
      this.title = "查看"
      this.drawer = true;
    })
  },
   //修改按钮
    updatePaySubject(row){
      queryDeptById(row.id).then(response =>{
        console.log(response
        )
      this.form2 = response;                                                                                                                                                                                                                                                                                                            
      this.open= true;
      this.title = "编辑"
     })
   },
   //导出按钮
   handleExport() {
      this.download('aqsc/paySubject/export',{
      ...this.queryParams
      },`pay_${new Date().getTime()}.xlsx`)
   },
    //导入按钮操作 
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
        /** 下载模板操作 */
        importTemplate() {
      this.download('system/user/importTemplate', {
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
   //取消
    cancel(){
      this.form2= {};
      this.open = false;
    },
   //唯一约束
    byCoding(){
      queryIdByCoding(coding).then(response =>{
        this.form = response;
      })
    },
   //提交按钮
    submitForm: function() {
        this.$refs["form1"].validate(valid => {
          if (valid) {
            if (this.form2.id != undefined) {
              edit(this.form2).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              save(this.form2).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.form2={}; 
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  },
//生命周期 - 创建完成（可以访问当前this实例）
created() {

},
//生命周期 - 挂载完成（可以访问DOM元素）
mounted() {
this.getList(),
this.getDeptName();
},
beforeCreate() {}, //生命周期 - 创建之前
beforeMount() {}, //生命周期 - 挂载之前
beforeUpdate() {}, //生命周期 - 更新之前
updated() {}, //生命周期 - 更新之后
beforeDestroy() {}, //生命周期 - 销毁之前
destroyed() {}, //生命周期 - 销毁完成
activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类

//设置新增表格样式
.frame{
    .el-form-item {
      .el-input {
        width: 300px;
      }
      .el-select{
        width: 300px;
      }
    }
  }
</style>